package com.wn.class30.cotroller.weixin;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.wn.class30.entity.*;
import com.wn.class30.mapper.MealPayDao;
import com.wn.class30.mapper.UserDao;
import com.wn.class30.service.IntegralService;
import com.wn.class30.service.UserService;
import com.wn.class30.service.VipService;
import com.wn.class30.service.WXPayOrderService;
import com.wn.class30.tools.MoneyUtils;
import com.wn.class30.tools.UserIp;
import com.wn.class30.tools.UseridUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.weixin4j.spring.WeixinTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping(value = "/weixin")
public class    AliTest2 {

    @Resource
    private UserService userService;
    @Resource
    private WeixinTemplate weixinTemplate;
    @Resource
    private UseridUtils useridUtils;
    @Resource
    private WXPayOrderService wxPayOrderService;

    @Resource
    private IntegralService integralService;
    @Resource
    private MealPayDao mealPayDao;
    @Resource
    UserDao userDao;

    @Resource
    private VipService vipService;
    private final String APP_ID = "2016102100729234";
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCAABjaTTfn7HVmykzf70hLT6+mthvxnj7PvWKrUcB6ic2gI8R1egX/pb9342CVoKUHNdG2CQfKRdRgJUHAFRQj/Rt+B2mhiO2KwmL3s64VYLVvGXHrH1mIpYJKRcfgnHJPDO3wxQtJZOKKPGKJ4wNdGCNk69Nu5R37u0f6qK6aT6kFuI0Z4AIBFSwp4l8Zx1tPIb1qjGziRDkZNYmO7UGXkx4dIIU85T8eBiIgbaO4oK0GPC3M35/x4TjhgdW2fNqpy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DDr6PFpXVm0cTt7zFzdWlYvtBkmZwT+UEUjemsU4j6GT17GkCgYEAu8dUTmlxSF+JZJm9TbkRNcQk7hKOAcz9w2BS1AcILtAZoVGvnW3Iz4l7ln2R8hDIAH89KaH0kyFMcY72eNRGKYmRKhJdCOk+FRl2E3iTl05qc0UVJSyMTeDD+k6qhJoF3oNWq4LauQg/XRxqL9KY+wqMbdTfhNj0hz/K13stSyI=";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqWprmMxJnks9IZdognbilVqyx0XFSi0xwujCiWQntaQDVskaDcWOImx3QNryJggG0uBd47gzx4RDJMT6ooyEW/w34t6559w0F4evqAWudHgKMjTjbk85lIk7PiLujheFbaSHwkVPvp2w3nJEJTaFopkt7QVGc6g58A+rYB5YPAkdhhUV4Ve2nvAGvG9AMejPQdZE4gvLuxbBoWS3vUvSLnij5MdYEUIf7eK9BBZ/WHTwgMQBwf2l0maJEITV90G6ntiaYy2hK1/au+etWfqo/bga2a2wPvQ/uZLFsI5WA1PfTjsspQjTk8RpY0NmzaW2gEoTvfN2AMA1RbrqhmtOWQIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
//    private final String NOTIFY_URL = "http://zhouhao1.ngrok2.xiaomiqiu.cn/weixin/notifyUrl2";
    private final String NOTIFY_URL = "http://wchuan.mynatapp.cc/weixin/notifyUrl2";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
//    private final String RETURN_URL = "http://zhouhao1.ngrok2.xiaomiqiu.cn/weixin/returnUrl2";
    private final String RETURN_URL = "http://wchuan.mynatapp.cc/weixin/returnUrl2";

    @RequestMapping("/alipay2")
    public void alipay2(HttpServletResponse httpResponse,Double btnPrice,String num) throws IOException {

        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no = num;
        //付款金额，必填
        String total_amount = btnPrice.toString();
        //订单名称，必填
        String subject ="升级会员";
        //商品描述，可空
        String body = "尊敬的会员欢迎购买奥迪A8 2016款 A8L 60 TFSl quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    @RequestMapping(value = "alitelpay2")//http://wchuan.mynatapp.cc/weixin/pay/alixianxiapay.html
    public void alitelpay2(HttpServletRequest httpRequest, HttpServletResponse response,Double payMoney) throws Exception {
        AlipayClient client = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        String orderIdByTime = UserIp.getOrderIdByTime();
        model.setOutTradeNo(orderIdByTime);
        model.setSubject("禄舍轩商城");
        model.setTotalAmount(payMoney+"");
        model.setBody("尊敬的用户欢迎到禄舍轩连锁店消费");
        model.setTimeoutExpress("2m");
        model.setProductCode("QUICK_WAP_WAY");
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setReturnUrl(RETURN_URL);
        alipay_request.setNotifyUrl(NOTIFY_URL);
        // 设置同步地址
//        PayOrder payOrder = new PayOrder();
//        payOrder.setBussinessId((Integer) httpRequest.getSession().getAttribute("wxpaybusinessid"));
//        payOrder.setPayMoney(payMoney);
//        payOrder.setPayOrderState("0");
//        payOrder.setPayUpdateTime(new Date());
//        payOrder.setPayOrderNumber(orderIdByTime);
//        payOrder.setUserId(useridUtils.queryUseridByOptenid(httpRequest));
//        wxPayOrderService.insertPayOrder(payOrder);
        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            System.out.println(form);
            response.setContentType("text/html;charset=" + CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    @RequestMapping(value = "returnUrl2")
    public String returnUrl2(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //支付成功，修复支付状态
    /*        payService.updateById(Integer.valueOf(out_trade_no));*/
            return "/weixin/queryIndex";//跳转付款成功页面
        }else{
            return "fail";//跳转付款失败页面
        }

    }

    @RequestMapping(value = "notifyUrl2")
    public void notifyUrl2(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("=================================异步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+trade_no);
            System.out.println("付款金额="+total_amount);

            //查询会员套餐、积分、等级、
            String s = out_trade_no.split("6699")[1];
            MealPay mealPay = mealPayDao.selectByPrimaryKey(Integer.parseInt(s));
            if("0".equals(mealPay.getMealpayStatus())){
                System.out.println("状态为0");
                //更改订单状态
                mealPay.setMealpayStatus("1");
                mealPayDao.updateByPrimaryKeySelective(mealPay);
                //更爱用户积分

                List<Map<String,Object>> mealAndVip = userService.selectMealAndVip(mealPay.getMealId());
                System.out.println("mealAndVip:"+mealAndVip);
                //查询用户信息
                UserExample userExample = new UserExample();
                UserExample.Criteria criteria = userExample.createCriteria();
                criteria.andTelEqualTo(mealPay.getUsertel());
                List<User> users = userDao.selectByExample(userExample);
                User user = users.get(0);

                //更改用户成长值和会员id
                userService.updateUserByMealAndVip(user.getUserId(),mealAndVip.get(0));

            }




            //支付成功，修复支付状态
            /*        payService.updateById(Integer.valueOf(out_trade_no));*/
            response.getWriter().write("success");
        }else{
            response.getWriter().write("fail");
        }
    }
}


